package com.yellowframework.cloud.aspect;

import com.yellowframework.cloud.common.annotation.FeignLogin;
import com.yellowframework.cloud.common.constant.Constants;
import com.yellowframework.cloud.common.exception.ExceptionCast;
import com.yellowframework.cloud.common.model.response.CommonCode;
import com.yellowframework.cloud.utils.RedisUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.UUID;

/**
 * feign免登录验证
 * @author Hao.
 * @version 1.0
 * @since 2023/6/15 11:09
 */
@Aspect
@Component
public class FeignLoginAspect {

	@Resource
	private RedisUtils redisUtils;

	@Pointcut("@annotation(com.yellowframework.cloud.common.annotation.FeignLogin)")
	public void check() {}

	@Before("check() && @annotation(feignLogin)")
	public void main(FeignLogin feignLogin) {
		final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
		final boolean client = feignLogin.client();
		// 客户端，生产一个通行证，方便服务端消费
		if (client) {
			final String pass = UUID.randomUUID().toString();
			// feign通行证有效期10秒
			redisUtils.set(Constants.FEIGN_LOGIN_KEY + pass, "pass", 10L);

			request.setAttribute(Constants.FEIGN_LOGIN_KEY, pass);
			return;
		}

		// 服务端，验证并消费通行证

		final Object key = request.getHeader(Constants.FEIGN_LOGIN_KEY.replace(":", ""));

		// 非法调用
		if (Objects.isNull(key) || !redisUtils.exists(Constants.FEIGN_LOGIN_KEY + key)) {
			ExceptionCast.cast(CommonCode.INVALID_FEIGN_REQUEST);
		}
		redisUtils.delete(Constants.FEIGN_LOGIN_KEY + key);
	}

}
